﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Common.Library;
using Common.Utilities;
using FlurryWP8SDK.Models;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using AdRotator;

namespace OnlineMovies.Views
{
    public class YouTubeUri
    {
        internal string url;

        public Uri Uri { get { return new Uri(url, UriKind.Absolute); } }
        public int Itag { get; set; }
        public string Type { get; set; }

        public bool IsValid
        {
            get { return url != null && Itag > 0 && Type != null; }
        }
    }
    public partial class Youtube : PhoneApplicationPage
    {
        public  string YoutubeID = string.Empty;
        public Youtube()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            {
                Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                if (Adc != null)
                {
                    Adc.IsAdRotatorEnabled = true;
                    Adc.Visibility = Visibility.Visible;
                    Adc.Invalidate();
                }
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            {
                Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                if (Adc != null)
                {
                    Adc.IsAdRotatorEnabled = false;
                    Adc.Visibility = Visibility.Collapsed;
                }
            }
            string myid=string.Empty;
            if (NavigationContext.QueryString.TryGetValue("myid", out myid))
            {
                PlayYoutubeVideo(myid);
            }
          
        }
        public  void PlayYoutubeVideo(string url)
        {
            YoutubeID = url;
            WebClient client = new WebClient();
            client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
            string uri = "http://www.youtube.com/watch?v=" + url;
            client.DownloadStringCompleted += client_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri(uri, UriKind.RelativeOrAbsolute));




        }

         void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    GethtmlData(e.Result);
                }
                else
                {
                    UtilitiesManager.LoadBrowserTask(YoutubeID);
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in client_DownloadStringCompleted Method In Youtube.cs file", ex);
            }
        }
        public  void GethtmlData(string rawHtml)
        {
            string title = string.Empty;
            var urls = new List<YouTubeUri>();
            var urlsfor480p = new List<YouTubeUri>();
            var uri = default(Uri);
            try
            {
                var match = Regex.Match(rawHtml, "url_encoded_fmt_stream_map\": \"(.*?)\"");
                var data = Uri.UnescapeDataString(match.Groups[1].Value);

                var arr = Regex.Split(data, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); // split by comma but outside quotes
                foreach (var d in arr)
                {
                    var url = "";
                    var signature = "";
                    var tuple = new YouTubeUri();
                    foreach (var p in d.Replace("\\u0026", "\t").Split('\t'))
                    {
                        var index = p.IndexOf('=');
                        if (index != -1 && index < p.Length)
                        {
                            try
                            {
                                var key = p.Substring(0, index);
                                var value = Uri.UnescapeDataString(p.Substring(index + 1));
                                if (key == "url")
                                    url = value;
                                else if (key == "itag")
                                    tuple.Itag = int.Parse(value);
                                else if (key == "type" && value.Contains("video/mp4"))
                                    tuple.Type = value;
                                else if (key == "sig")
                                    signature = value;
                            }
                            catch { }
                        }
                    }

                    tuple.url = url + "&signature=" + signature;
                    if (tuple.IsValid)
                        urls.Add(tuple);
                }

                var minTag = GetQualityIdentifier(YouTubeQuality.Quality720P);
                var maxTag = GetQualityIdentifier(YouTubeQuality.Quality720P);
                urlsfor480p.AddRange(urls);
                foreach (var u in urls.Where(u => u.Itag < minTag || u.Itag > maxTag).ToArray())
                    urls.Remove(u);

                var entry = urls.OrderByDescending(u => u.Itag).FirstOrDefault();
                if (entry == null)
                {
                    minTag = GetQualityIdentifier(YouTubeQuality.Quality480P);
                    maxTag = GetQualityIdentifier(YouTubeQuality.Quality480P);
                    foreach (var u in urlsfor480p.Where(u => u.Itag < minTag || u.Itag > maxTag).ToArray())
                        urlsfor480p.Remove(u);

                    entry = urlsfor480p.OrderByDescending(u => u.Itag).FirstOrDefault();
                }


                if (entry != null)
                {

                    uri = new Uri(entry.url);

                }
                if (uri != null)
                {


                 
                    List<Parameter> Params = new List<Parameter> { new Parameter(AppSettings.LinkType, AppSettings.LinkTitle) };
                    FlurryWP8SDK.Api.LogEvent(AppSettings.Title, Params);
                    LoadVideoPlayer(uri.ToString());
                }

                else
                {
                    AppSettings.startplaying = false;
                    AppSettings.startplayingforpro = false;
                    UtilitiesManager.LoadBrowserTask(YoutubeID);
                    FlurryWP8SDK.Api.LogError("youtube link not working", null);
                }
            }
            catch (Exception ex)
            {
                AppSettings.startplaying = false;
                AppSettings.startplayingforpro = false;
                UtilitiesManager.LoadBrowserTask(YoutubeID);
                Exceptions.SaveOrSendExceptions("Exception in GethtmlData Method In Youtube.cs file", ex);
            }



        }
        private  void LoadVideoPlayer(string url)
        {
            BackgroundAudioPlayer.Instance.Close();
            mediaplayer.Source = new Uri(url, UriKind.Absolute);
            mediaplayer.Play();
        }
        public static int GetQualityIdentifier(YouTubeQuality quality)
        {
            switch (quality)
            {
                case YouTubeQuality.Quality480P: return 18;
                case YouTubeQuality.Quality720P: return 22;
                case YouTubeQuality.Quality1080P: return 37;
            }
            throw new ArgumentException("maxQuality");
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //e.Cancel = true;
            List<Parameter> Params = new List<Parameter> { new Parameter(AppSettings.LinkType, AppSettings.LinkTitle) };
            FlurryWP8SDK.Api.EndTimedEvent(AppSettings.Title, Params);
           if(ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            AppSettings.startplaying = false;
            else
               AppSettings.startplayingforpro = false;
         
               while (NavigationService.BackStack.Count() > 1)
               {
                   if (NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("Youtube") || NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("Advertisement") )
                   {
                       NavigationService.RemoveBackEntry();

                   }
                   else
                       break;
               }
         
           
        }
        private void mediaplayer_MediaEnded_1(object sender, Microsoft.PlayerFramework.MediaPlayerActionEventArgs e)
        {
            List<Parameter> Params = new List<Parameter> { new Parameter(AppSettings.LinkType, AppSettings.LinkTitle) };
            FlurryWP8SDK.Api.EndTimedEvent(AppSettings.Title, Params);
            if (AppSettings.startplayingforpro == true && (ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString() || ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName != Apps.Story_Time_Pro.ToString()))
            {

                if (Constants.YoutubePlayList.Count > 0)
                {
                    AppSettings.LinkUrl = Constants.YoutubePlayList.FirstOrDefault().Key;
                    AppSettings.LinkTitle = Constants.YoutubePlayList.FirstOrDefault().Value;
                    Constants.YoutubePlayList.Remove(Constants.YoutubePlayList.FirstOrDefault().Key);
                    AppSettings.PlayVideoTitle = Constants.YoutubePlayList.FirstOrDefault().Value;
                    PlayYoutubeVideo(AppSettings.LinkUrl);
                }
                else if (Constants.YoutubePlayList.Count == 0)
                {
                    AppSettings.startplayingforpro = false;
                    NavigationService.GoBack();
                }
            }
            else if (AppSettings.startplaying == true && ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            {
               
                if (Constants.YoutubePlayList.Count > 0)
                {
                   
                    PageHelper.RootApplicationFrame.Navigate(new Uri("/Views/Advertisement.xaml", UriKind.RelativeOrAbsolute));
                }
               else if (Constants.YoutubePlayList.Count == 0)
                {
                    AppSettings.startplaying = false;
                    while (NavigationService.BackStack.Count() > 1)
                    {
                        if (NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("Youtube") || NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("Advertisement"))
                        {
                            NavigationService.RemoveBackEntry();
                           
                        }
                        else
                            break;
                    }
                    NavigationService.GoBack();
                }
            }
            else
                NavigationService.GoBack();
        }

        private void mediaplayer_MediaFailed_1(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void mediaplayer_MediaOpened_1(object sender, RoutedEventArgs e)
        {
            List<Parameter> Params = new List<Parameter> { new Parameter(AppSettings.LinkType, AppSettings.LinkTitle) };
            FlurryWP8SDK.Api.LogEvent(AppSettings.Title, Params,true);
            //FlurryWP8SDK.Api.LogEvent(AppSettings.Title+"-"+AppSettings.PlayVideoTitle, true);
        }
    }
}